using System.Collections.Generic;
using System.Xml;

namespace Hvam.SharePoint.Search.Query.Site.Models
{
    internal class SiteSearchResults
    {
        public List<Dictionary<string, string>> Results { get; set; }

        public int TotalResults { get; set; }

        public int NumberOfResults
        {
            get
            {
                return Results == null ? 0 : Results.Count;
            }
        }

        public SiteSearchResults()
        {
            Results = new List<Dictionary<string, string>>();
        }

        public XmlDocument GetXmlDocument()
        {
            var xmlDocument = new XmlDocument();

            var root = xmlDocument.AppendChild(xmlDocument.CreateElement("All_Results"));

            if (Results != null)
            {
                foreach (var result in Results)
                {
                    var row = xmlDocument.CreateElement("Result");
                    
                    foreach (var pair in result)
                    {
                        var value = xmlDocument.CreateElement(pair.Key);

                        value.InnerText = pair.Value ?? string.Empty;

                        row.AppendChild(value);
                    }

                    root.AppendChild(row);
                }
            }

            var total = xmlDocument.CreateElement("TotalResults");
            total.InnerText = TotalResults.ToString();
            root.AppendChild(total);

            var number = xmlDocument.CreateElement("NumberOfResults");
            number.InnerText = NumberOfResults.ToString();
            root.AppendChild(number);

            return xmlDocument;
        }
    }
}